<template>
	<view class="container">
		<view class="tui-chatroom-navigatorbar">
			<image class="tui-chatroom-navigatorbar-back" src="../static/static/assets/ic_back_white.svg"
				@tap="goBack" />
			<!-- 先查 remark；无 remark 查 (c2c)nick/(group)name；最后查 (c2c)userID/(group)groupID -->
			<view style="font-weight: bold;" class="conversation-title">{{ conversationName }}</view>
		</view>
		<view class="menu-block">
			<block v-if="identity==1">
				<view @click="exchangePhone" class="menu-item">
					<image :src="imageUrl+'/chat/phone.png'" mode="heightFix" class="menu-icon"></image>
					<view class="menu-name">打电话</view>
				</view>
				<!-- <view class="menu-item">
					<image :src="imageUrl+'/chat/wechat.png'" mode="heightFix" class="menu-icon"></image>
					<view class="menu-name">换微信</view>
				</view> -->
				<view @click="resume(1)" class="menu-item">
					<image :src="imageUrl+'/chat/resume.png'" mode="heightFix" class="menu-icon"></image>
					<view class="menu-name">发简历</view>
				</view>
			</block>
			<block v-if="identity==2">
				<view @click="resume(2)" class="menu-item">
					<image :src="imageUrl+'/chat/resume.png'" mode="heightFix" class="menu-icon"></image>
					<view class="menu-name">求简历</view>
				</view>
				<view @click="exchangePhone" class="menu-item">
					<image :src="imageUrl+'/chat/phone.png'" mode="heightFix" class="menu-icon"></image>
					<view class="menu-name">打电话</view>
				</view>
				<!-- <view class="menu-item">
					<image :src="imageUrl+'/chat/wechat.png'" mode="heightFix" class="menu-icon"></image>
					<view class="menu-name">换微信</view>
				</view> -->
				<view @click="interview" class="menu-item">
					<image :src="imageUrl+'/chat/interview.png'" mode="heightFix" class="menu-icon"></image>
					<view class="menu-name">面试TA</view>
				</view>
			</block>
		</view>
		<view @tap="triggerClose" class="message-list">
			<TUI-message-list id="message-list" ref="messageList" :conversation="conversation" />
		</view>
		<view v-if="videoPlay" class="container-box" @tap.stop="stopVideoHander">
			<video v-if="videoPlay" class="video-message" :src="videoMessage.payload.videoUrl"
				:poster="videoMessage.payload.thumbUrl" object-fit="cover" error="videoError" autoplay="true"
				direction="0" />
		</view>
		<view v-if="showChat" class="message-input">
			<TUI-message-input id="message-input" ref="messageInput" :conversation="conversation"
				@sendMessage="sendMessage" />
		</view>
		<tuicallkit ref="TUICallKit" id="TUICallKit-component" :config="config"></tuicallkit>
	</view>
</template>

<script>
	import TUIMessageList from '../components/tui-chat/message-list/index';
	import TUIMessageInput from '../components/tui-chat/message-input/index';
	import {
		getPhoneByImUserID,
		getToAccount
	} from '@/util/im.js';
	import { mapGetters } from 'vuex';
	const app = getApp();
	export default {
		components: {
			TUIMessageList,
			TUIMessageInput
		},
		props: {},
		data() {
			return {
				conversationName: '',
				conversation: {},
				messageList: [],
				showChat: true,
				conversationID: '',
				//视频播放
				videoPlay: false,
				videoMessage: {},
				config: {
					sdkAppID: '',
					userID: '',
					userSig: '',
					type: 1,
					tim: null
				},
				imageUrl: '',

			};
		},
		computed: {
			identity() {
				return this.$store.getters.identity
			}
		},
		created() {
			//监听视频播放
			uni.$on('videoPlayerHandler', value => {
				this.videoPlay = value.isPlay;
				this.videoMessage = value.message;
			});
		},
		onLoad(options) {
			const conversationID = options.conversationID;
			this.setData({
				conversationID
			});
			//修改已读状态
			this.setMessageRead({
				conversationID
			})
			//获取会话详情
			uni.$TUIKit.getConversationProfile(conversationID).then(res => {
				const {
					conversation
				} = res.data;
				this.conversation = conversation;
				this.setData({
					conversationName: this.getConversationName(conversation)
				});
			});

			this.imageUrl = this.globalConfig.imageUrl;

			//监听消息列表更新
			uni.$on('updateMessageList', (message) => {
				this.setMessageRead({
					conversationID
				})
				this.$refs.messageList.updateMessageList(message);
			})
			//初始化音视频参数
			let config = {
				userName:this.$store.getters.user.realName,
				userSig:this.$store.getters.userSig,
				sdkAppID:this.$store.getters.sdkAppID,
				userID:this.$store.getters.userID,
				tim: wx.$TIM
			}
			//初始化音视频
			this.$nextTick(() => {
				this.$refs.TUICallKit.init(config)
			})
			//监听开始面试操作
			uni.$on('startInterview', (interviewID) => {
				this.call();
			})
		},
		onUnload() {
			this.$refs.TUICallKit.destroyed()
		},
		methods: {
			setMessageRead(options) {
				uni.$TUIKit.setMessageRead(options)
			},
			//发起视频通话
			call() {
				const settingPromise = new Promise((resolve, reject) => { //获取授权状态
					uni.getSetting({
						success: (getRes) => {
							resolve(getRes.authSetting);
						},
						fail: (getRes) => {
							this.showToast('获取授权状态失败！');
							reject(getRes);
						}
					})
				})
				settingPromise.then((res) => {
					var auth = res;
					const recordPromise = new Promise((resolve, reject) => { //获取授权状态
						if (!auth['scope.record']) { //若无麦克风授权则尝试授权
							uni.authorize({
								scope: 'scope.record',
								success: () => {
									resolve();
								},
								fail: () => {
									this.showAuthModal('未获取到麦克风权限，请在设置页开启权限！');
									reject();
								}
							})
						} else {
							resolve();
						}
					})
					recordPromise.then(() => { //麦克风授权成功检查摄像头
						const cameraPromise = new Promise((resolve, reject) => {
							if (!auth['scope.camera']) {
								uni.authorize({
									scope: 'scope.camera',
									success: () => {
										resolve()
									},
									fail: () => {
										this.showAuthModal('未获取到摄像头权限，请在设置页开启权限！');
										reject()
									}
								})
							} else {
								resolve()
							}
						}).then(() => {
							this.$refs.TUICallKit.call({
								userID: getToAccount(this.conversation),
								type: 2
							})
						})
					})
				})
			},
			showAuthModal(content) {
				uni.showModal({
					title: '提示',
					content: content,
					confirmText: '去设置',
					showCancel: false,
					success: (recordModalRes) => {
						if (recordModalRes.confirm) {
							uni.openSetting()
						}
					}
				})
			},
			interview() {
				const to = getToAccount(this.conversation);
				uni.navigateTo({
					url: `/page_other/interview/create?name=${this.conversationName}&mobile=${getPhoneByImUserID(to)}&userID=${to}`
				})
			},
			//交换电话
			exchangePhone() {
				uni.showModal({
					title: '提示',
					content: '确定与对方交换电话号码吗',
					success: (e) => {
						if (e.confirm) {
							console.log(getToAccount(this.conversation))
							const message = uni.$TUIKit.createCustomMessage({
								to: getToAccount(this.conversation),
								conversationType: uni.$TUIKitTIM.TYPES.CONV_C2C,
								payload: {
									data: 'exchangePhone',
									description: '交换电话号',
									extension: JSON.stringify({
										phone: this.$store.getters.user.mobile,
										agree: null
									})
								}
							})
							uni.$TUIKit.sendMessage(message).then((messageRes) => {
								this.$refs.messageList.updateMessageList(message);
							}).catch(() => {
								this.showToast('操作失败，请重试！');
							})
						}
					}
				})
			},
			//简历请求
			resume(type) {
				uni.showModal({
					title: '提示',
					content: `确定向对方${type === 1 ? '发送' : '获取'}简历吗？`,
					success: (e) => {
						if (e.confirm) {
							const message = uni.$TUIKit.createCustomMessage({
								to: getToAccount(this.conversation),
							 conversationType: uni.$TUIKitTIM.TYPES.CONV_C2C,
								payload: {
									data: type === 1 ? 'sendResume' : 'getResume',
									description: '',
									extension: JSON.stringify({
										agree: null
									})
								}
							})
							uni.$TUIKit.sendMessage(message).then((messageRes) => {
								this.$refs.messageList.updateMessageList(message);
							}).catch(() => {
								this.showToast('操作失败，请重试！');
							})
						}
					}
				})
			},
			stopVideoHander() {
				this.videoPlay = false;
			},
			triggerClose() {
				if (this.showChat) {
					this.$refs.messageInput.handleClose();
				}
			},
			getConversationName(conversation) {
				if (conversation.type === '@TIM#SYSTEM') {
					this.setData({
						showChat: false
					});
					return '系统通知';
				}

				if (conversation.type === 'C2C') {
					return conversation.remark || conversation.userProfile.nick || conversation.userProfile.userID;
				}

				if (conversation.type === 'GROUP') {
					return conversation.groupProfile.name || conversation.groupProfile.groupID;
				}
			},

			sendMessage(event) {
				console.log(event)
				// 将自己发送的消息写进消息列表里面
				this.$refs.messageList.updateMessageList(event.detail.message);
			},

			goBack() {
				uni.navigateBack({
					delta: 1
				});
			}
		}
	};
</script>
<style lang="scss">
	@import './index.css';

	.menu-block {
		width: 100%;
		display: flex;
		flex-direction: row;
		align-items: center;
		height: 120rpx;
		border-bottom: 1px solid #efefef;
		box-shadow: 0 0 0 0 #efefef;

		.menu-item {
			flex-grow: 1;
			display: flex;
			flex-direction: column;
			align-items: center;
			justify-content: center;

			.menu-icon {
				height: 40rpx;
			}

			.menu-name {
				font-size: 28rpx;
				margin-top: 10rpx;
			}
		}
	}
</style>
